﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using Barbar.UrlGuard.BL;

namespace Barbar.UrlGuard.Dal.Persist {
  public class XmlDataContextPersistor : IDataContextPersistor {
    private string m_FileName;
    private ILogger m_Logger;
    
    private static object m_SyncRoot = new object();
    private static XmlSerializer m_DataContextSerializer = new XmlSerializer(typeof(DataContext));
      
    public XmlDataContextPersistor(string fileName, ILogger logger) {
      if (string.IsNullOrEmpty(fileName)) {
        throw new ArgumentNullException("fileName");
      }

      if (logger == null) {
        throw new ArgumentNullException("logger");
      }

      m_FileName = fileName;
      m_Logger = logger;
    }

    #region IDataContextPersistor Members

    public void Persist(DataContext dataContext) {
      if (dataContext == null)
        throw new ArgumentNullException("dataContext");

      lock (m_SyncRoot) {
        using (FileStream stream = new FileStream(m_FileName, FileMode.Create, FileAccess.Write, FileShare.None)) {
          m_DataContextSerializer.Serialize(stream, dataContext);
        }
      }
    }

    public DataContext Load() {
      lock (m_SyncRoot) {
        DataContext result = null;
        try {
          using (FileStream stream = new FileStream(m_FileName, FileMode.Open, FileAccess.Read, FileShare.Read)) {
            result = (DataContext)m_DataContextSerializer.Deserialize(stream);
          }
        } catch (Exception exception) {
          m_Logger.Fatal("Failed to read configuration file from disc, creating empty default configuration.", exception);
        }
        return result ?? new DataContext();
      }
    }

    #endregion
  }
}
